import React, { memo, useEffect, useRef, useState } from 'react';
import {
  ConfigProvider,
  Divider,
  Table,
  Modal,
  Button,
  Form,
  Input,
  Popconfirm,
  Space,
  Dropdown,
  message,
  Drawer,
  Menu,
  Descriptions,
  Col,
  Row
} from 'antd';
import { ProForm } from '@/base-ui';
import DivWrapper from './style';
import zhCN from 'antd/es/locale/zh_CN';
import http from '@/services/request';
import TipsHeader from '@/components/TipsHeader';
import chickenHousePicture from '@/assets/img/chicken-house.png';
import {
  PageSearchConfig,
  SearchSelector,
  DataType,
  UseSearch
} from './config';

//form
const NewForm = (props: any) => {
  return (
    <Form ref={props.newref} layout={'vertical'}
      style={{ minHeight: '100%', flex: 1, overflow: 'auto', width: '100%', overflowX: 'hidden' }}>
      <Row >
       <Col xs={{ span: 5, offset: 4 }} lg={{ span: 6, offset: 4 }}>
      <Form.Item
        label="鸡舍编号"
        name="chickenHouseId"
        rules={[{ required: true, message: '请输入鸡舍编号' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="chickenHouseName"
        label="鸡舍名"
        rules={[{ required: true, message: '请输入鸡舍名' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        label="照明灯数量"
        name="lightQuantity"
        rules={[{ required: true, message: '请输入照明灯数量' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        label="最大容纳鸡苗量"
        name="maximumQuantity"
        rules={[{ required: true, message: '请输入最大容纳鸡苗量' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="area"
        label="鸡舍面积"
        rules={[{ required: true, message: '请输入鸡舍面积' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="responsibleName"
        label="鸡舍负责人"
        rules={[{ required: true, message: '请输入鸡舍负责人' }]}
      >
        <Input />
      </Form.Item>
        </Col>
       <Col xs={{ span: 5, offset: 4 }} lg={{ span: 6, offset: 4 }}>
      <Form.Item
        name="responsiblePhone"
        label="联系方式"
        rules={[{ required: true, message: '请输入联系方式' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="sinkQuantity"
        label="水槽数"
        rules={[{ required: true, message: '请输入水槽数' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="tankQuantity"
        label="饲料槽数"
        rules={[{ required: true, message: '请输入饲料槽数' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="device"
        label="设备编号"
        rules={[{ required: true, message: '请输入设备编号' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="remark"
        label="备注"
        rules={[{ required: true, message: '请备注' }]}
      >
        <Input />
      </Form.Item>
        </Col>
      </Row >
    </Form>
  );
};

//按钮组
const Buttongroup = (props: any) => {
  return (
    <div style={{ marginBottom: 10, float: 'left' }}>
      <Button
        type="primary"
        onClick={() => props.add()}
        style={{ marginRight: 10 }}
      >
        新增鸡舍
      </Button>
      <Button
        danger
        onClick={() => {
          props.checkIt();
        }}
        style={{ marginRight: 10 }}
      >
        批量删除
      </Button>


    </div>
  );
};

const BuyBack = memo(() => {
  //更多功能定位id
  const [Drawerid, setDrawerid]: any = useState({});
  //抽屉开关
  const [DrawerVisible, setDrawerVisible] = useState(false);
  //复选框批量删除
  const [itemSelected, setItemSelected] = useState<React.Key[]>([]);

  //是否新增
  const [edited, setedited]: any = useState('');
  //高级检索
  const [isMoreSearchShow, setisMoreSearchShow]: any = useState(false);
  const newref: any = useRef();
  const [dataSource, setdataSource]: any = useState([]);
  const [searchMore, setSearchMore] = useState(false);

  // 控制对话框显示（新增）
  const [addModalVisible, setAddModalVisible] = useState(false);

  useEffect(() => {
    http.get('/feed/chicken/chickenHouseFarming/list/1/30').then((res) => {
      setdataSource(res.data.records);
    });
  }, []);

  const rowSelection = {
   onChange: (selectedRowKeys: React.Key[]) => {
      setItemSelected(selectedRowKeys);
    },
    getCheckboxProps: (record: DataType) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name
    })
  };

  const checkIt = () => {
    http({
      url: `/feed/chicken/chickenHouseFarming/deletion/batch`,
      method: 'delete',
      data: JSON.stringify(itemSelected),
      headers: { 'Content-Type': 'application/json' }
    }).then(() => {
      http.get('/feed/chicken/chickenHouseFarming/list/1/30').then((res) => {
        setdataSource(res.data.records);
      });
    });
  };

  //导出
  const exported = () => {
    http({
      method: 'get',
      url: '/server/dailySlaughter/export',
      data: JSON.stringify([1, 4]),
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/json'
      }
    }).then((res: any) => {
      const blob = new Blob([res.data], {
        // res 为后台返回数据
        type: 'application/vnd.ms-excel;charset=utf-8' // 导出数据生成excel的格式设置
      });
      if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a');
        elink.download = Date.now() + `.xlsx`;
        elink.style.display = 'none';
        elink.target = '_blank';
        elink.href = window.URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
      }
    });
  };

  // 对话框确认
  const handleAddModalOk = () => {
    setAddModalVisible(false);
    // 修改操作
    if (edited) {
      const newedited = newref.current.getFieldsValue();
      http
        .put(
          `/feed/chicken/chickenHouseFarming/update/${edited.chickenHouseId}`,
          {
            ...newedited
          }
        )
        .then(() => {
          http
            .get('/feed/chicken/chickenHouseFarming/list/1/30')
            .then((res) => {
              setdataSource(res.data.records);
            });
        });
      setedited(null);
      return;
    }
    //id不在--就是新增
    const addData = newref.current.getFieldsValue();
    const {
      chickenHouseId,
      chickenHouseName,
      lightQuantity,
      maximumQuantity,
      area,
      responsibleName,
      responsiblePhone,
      sinkQuantity,
      remark,
      tankQuantity,
      device
    } = addData;

    http
      .post('/feed/chicken/chickenHouseFarming/save', {
        chickenHouseId,
        chickenHouseName,
        lightQuantity,
        maximumQuantity,
        area,
        responsibleName,
        responsiblePhone,
        sinkQuantity,
        remark,
        tankQuantity,
        device
      })
      .then(() => {
        http.get('/feed/chicken/chickenHouseFarming/list/1/30').then((res) => {
          setdataSource(res.data.records);
        });
      })
      .catch((error) => {
        // eslint-disable-next-line no-console
        console.log(error);
      });
  };

  //编辑
  const edit = (id: any) => {
    setAddModalVisible(true);
    //这里必须单单setField..会报错："表单还没挂载调用了setFieldsValue",应该用异步，设一个定时器
    setTimeout(() => {
      newref.current.setFieldsValue({
        ...id
      });
      setedited(id);
    }, 0);
  };

  // 对话框取消
  const handleAddModalCancel = () => {
    setAddModalVisible(false);
  };
  const add = () => {
    setTimeout(() => {
      newref.current.setFieldsValue({
        repoId: '',
        batchNumber: '',
        productName: '',
        matName: '',
        supplier: '',
        money: '',
        cases: '',
        quantity: '',
        weight: '',
        unit: ''
      });
    });
    setAddModalVisible(true);
  };

  const indexTable = {
    pagination: {
      //每页10条项目
      defaultPageSize: 10,
      //自定义每页显示数目
      showSizeChanger: true,
      //当前的页数和大小
      onShowSizeChange: (current: any, pageSize: any) => {},
      //自定义每页显示项目的选项
      pageSizeOptions: ['1', '2', '3', '4', '5', '6', '8', '10'],

      // 输入指定页码跳页
      showQuickJumper: true,
      //跳页之后的回调函数
      onShowQuickJump: (page: any) => {},
      //全部项目数（最好可以用变量表示，与实际项目数关联）
      total: dataSource?.length,
      // 改变的回调函数
      onChange: (page: any) => {}
    }
  };

  const FormColumns: any = [
    {
      title: '鸡舍编号',
      dataIndex: 'chickenHouseId',
      key: 'chickenHouseId',
      width: 100
    },
    {
      title: '鸡舍名',
      dataIndex: 'chickenHouseName',
      key: 'chickenHouseName',
      width: 120
    },
    {
      title: '照明灯数量',
      dataIndex: 'lightQuantity',
      key: 'lightQuantity',
      width: 100
    },
    {
      title: '容纳鸡苗数量',
      dataIndex: 'maximumQuantity',
      key: 'maximumQuantity',
      width: 120
    },
    {
      title: '鸡舍面积',
      dataIndex: 'area',
      key: 'area',
      width: 100
    },
    {
      title: '鸡舍负责人',
      dataIndex: 'responsibleName',
      key: 'responsibleName',
      width: 100
    },
    {
      title: '联系电话',
      dataIndex: 'responsiblePhone',
      key: 'responsiblePhone',
      width: 100
    },
    {
      title: '水槽数',
      dataIndex: 'sinkQuantity',
      key: 'sinkQuantity',
      width: 100
    },
    {
      title: '饲料槽数',
      dataIndex: 'tankQuantity',
      key: 'tankQuantity',
      width: 100
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      width: 150
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 150,
      render: (_: any, record: any) => (
        <Space>
          <a onClick={() => edit(record)}>编辑</a>
          <Popconfirm
            title="确定删除?"
            okText="确认"
            cancelText="取消"
            onConfirm={() => {
              http
                .delete(
                  `/feed/chicken/chickenHouseFarming/delete/${record.chickenHouseId}`
                )
                .then(() => {
                  const newData = dataSource.filter(
                    (item: { chickenHouseId: any }) =>
                      item.chickenHouseId !== record.chickenHouseId
                  );
                  setdataSource(newData);
                });
            }}
          >
            <a style={{ color: '#ff4d4f' }}>删除</a>
          </Popconfirm>
          <Dropdown overlay={menu(record)}>
            <a
              onClick={(e) => {
                e.preventDefault();
              }}
            >
              ···
            </a>
          </Dropdown>
        </Space>
      ),
      fixed: 'right'
    }
  ];

  const menu = (item: any) => (
    <Menu
      items={[
        {
          key: 0,
          label: (
            <Button
              type="primary"
              onClick={() => {
                showDrawer(item);
              }}
            >
              详情
            </Button>
          )
        },
        {
          key: 2,
          label: (
            <Button
              onClick={function () {
                window.print();
              }}
            >
              打印
            </Button>
          )
        }
      ]}
    />
  );

  // 高级检索 条件查询 /server/feeVoucherSlaughter/get

  const onFinish = (form: any) => {
    http
      .post('/feed/chicken/chickenHouseFarming/get', form)
      .then((res: any) => {
        if (res.statusCode !== 20000) {
          return message.error('查询失败');
        }
        const data = res.data || [];
        setdataSource(data);
      });
  };
  //详情--抽屉
  const showDrawer = (data: any) => {
    setDrawerVisible(true);
    http
      .get(`/feed/chicken/chickenHouseFarming/get/${data.chickenHouseId}`)
      .then((res) => {
        setDrawerid(res.data);
      });
  };

  const onDraweClose = () => {
    setDrawerVisible(false);
  };

  const renderDescription = () => (
    <>
      <p>鸡舍管理是指对鸡舍内部的环境、设备、私聊、疫苗等进行管理和监控的一系列工作。鸡舍管理对于保障肉鸡健康生长、提高养殖效益具有重要作用。</p>
      <p>鸡舍管理是肉鸡养殖过程中非常重要的一环，它直接关系到肉鸡的生长和健康，同时也关系到养殖场主的经济效益。</p>
    </>
  )

  return (
    <DivWrapper>
      <TipsHeader imgSrc={chickenHousePicture} title="鸡舍信息管理" description={renderDescription()} />
      {searchMore && (
        <div>
          <ProForm formItems={PageSearchConfig} onFinish={onFinish} />
          <Divider style={{ margin: '10px 0 20px' }} />
        </div>
      )}
      <Buttongroup
        checkIt={() => checkIt()}
        add={() => add()}
        exported={() => exported()}
      />
      <UseSearch
        setisMoreSearchShow={(e: any) => {
          setisMoreSearchShow(e);
        }}
        isMoreSearchShow={isMoreSearchShow}
        setsearchMore={(e: boolean) => setSearchMore(e)}
      />
      <SearchSelector
        dataSource={(e: any) => setdataSource(e)}
      ></SearchSelector>
      <ConfigProvider locale={zhCN}>
        <Table
          dataSource={dataSource}
          columns={FormColumns}
          scroll={{ x: 1300 }}
          pagination={indexTable.pagination}
          rowKey={(i) => i.id}
          rowSelection={{
            type: 'checkbox',
            ...rowSelection
          }}
        />
      </ConfigProvider>
      <Drawer
        title="详情"
        placement="right"
        size="large"
        onClose={onDraweClose}
        visible={DrawerVisible}
      >
        <Descriptions
          title={`鸡舍编号：${Drawerid.chickenHouseId}`}
          bordered
          style={{ width: '450px' }}
        >
          <Descriptions.Item label="鸡舍名">
            {Drawerid.chickenHouseName}
          </Descriptions.Item>
          <Descriptions.Item label="照明灯数量">
            {Drawerid.lightQuantity}
          </Descriptions.Item>
          <Descriptions.Item label="最大容纳鸡苗数量">
            {Drawerid.maximumQuantity}
          </Descriptions.Item>
          <Descriptions.Item label="鸡舍面积">
            {Drawerid.area}
          </Descriptions.Item>
          <Descriptions.Item label="负责人名">
            {Drawerid.responsibleName}
          </Descriptions.Item>
          <Descriptions.Item label="联系方式">
            {Drawerid.responsiblePhone}
          </Descriptions.Item>
          <Descriptions.Item label="水槽数量">
            {Drawerid.sinkQuantity}
          </Descriptions.Item>
          <Descriptions.Item label="饲料槽数量">
            {Drawerid.tankQuantity}
          </Descriptions.Item>
          <Descriptions.Item label="设备号">
            {Drawerid.device}
          </Descriptions.Item>
          <Descriptions.Item label="负责人ID">
            {Drawerid.responsibleId}
          </Descriptions.Item>
          <Descriptions.Item label="备注">{Drawerid.remark}</Descriptions.Item>
        </Descriptions>
      </Drawer>
      <Modal
        width={'600px'}
        centered
        bodyStyle={{
          display: 'flex',
          flexDirection: 'column-reverse',

        }}
        title="新增鸡舍"
        visible={addModalVisible}
        onOk={handleAddModalOk}
        onCancel={handleAddModalCancel}
      >
        <NewForm newref={newref} />
      </Modal>
    </DivWrapper>
  );
});
export default BuyBack;
